// SPDX-FileCopyrightText: Adam Evyčędo
//
// SPDX-License-Identifier: GPL-3.0-or-later

package xyz.apiote.bimba.czwek.repo

import android.content.Context
import android.graphics.Typeface
import android.graphics.drawable.Drawable
import android.os.Parcelable
import android.text.Annotation
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.style.StyleSpan
import androidx.core.graphics.drawable.toDrawable
import kotlinx.parcelize.Parcelize
import xyz.apiote.bimba.czwek.RoundedBackgroundSpan
import xyz.apiote.bimba.czwek.api.LineStubV1
import xyz.apiote.bimba.czwek.api.LineStubV2
import xyz.apiote.bimba.czwek.api.LineStubV3
import xyz.apiote.bimba.czwek.repo.Stop.LineDecoration

@Parcelize
data class LineStub(val name: String, val kind: LineType, val colour: Colour) : LineAbstract, Parcelable {
	constructor(l: LineStubV1) : this(l.name, LineType.of(l.kind), Colour(l.colour))
	constructor(l: LineStubV2) : this(l.name, LineType.of(l.kind), Colour(l.colour))
	constructor(l: LineStubV3) : this(l.name, LineType.of(l.kind), Colour(l.colour))

	fun icon(context: Context, scale: Float = 1f): Drawable {
		return super.icon(context, kind, colour, scale).toDrawable(context.resources)
	}

	fun decorate(
		str: SpannableStringBuilder,
		decoration: LineDecoration,
		annotation: Annotation?
	): SpannableStringBuilder {
		val spanStart = if (annotation != null) {
			str.getSpanStart(annotation)
		} else {
			0
		}
		val spanEnd = if (annotation != null) {
			str.getSpanEnd(annotation)
		} else {
			str.length
		}

		val background = RoundedBackgroundSpan(colour.toInt(), textColour(colour))
		val ital = StyleSpan(Typeface.ITALIC)
		when (decoration) {
			LineDecoration.ITALICS -> str.setSpan(
				ital,
				spanStart, spanEnd,
				Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
			)

			LineDecoration.COLOUR -> {
				str.setSpan(
					background,
					spanStart, spanEnd,
					Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
				)
			}

			LineDecoration.NONE -> {}
		}

		return str
	}
}